package com.grape.transaction.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.grape.transaction.rabbitmq.entity.DispatchEntity;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 描述:DispatchConsumer  派单消费者
 * @author: myx
 * @date: 2019/6/10
 * Copyright © 2019-grape. All rights reserved.
 */
@Component
public class DispatchConsumer {


	@RabbitListener(queues = "order_dic_queue")
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		String messageId = message.getMessageProperties().getMessageId();
		String msg = new String(message.getBody(), "UTF-8");
		System.out.println("派单消费者接收消息:" + msg + ",消息id:" + messageId);
		JSONObject jsonObject = JSONObject.parseObject(msg);
		String orderId = jsonObject.getString("orderId");
		if (StringUtils.isEmpty(orderId)) {
			// 日志记录
			return;
		}
		DispatchEntity dispatchEntity = new DispatchEntity();
		// 订单id
		dispatchEntity.setOrderId(orderId);
		// 外卖员id
		dispatchEntity.setTakeoutUserId("123");
		// 外卖路线
		dispatchEntity.setDispatchRoute("40,40");
		try {
			//插入操作
			int insertDistribute = 1;
			if (insertDistribute > 0) {
				// 手动签收消息,通知mq服务器端删除该消息
				int i =1/0;
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				System.out.println("派单成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			// // 丢弃该消息
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		}
	}

}